package com.birdboot.core;

import com.birdboot.http.HttpServletRequest;
import com.birdboot.http.HttpServletResponse;

import java.io.*;
import java.net.Socket;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 该线程的任务是与指定的客户端完成HTTP交互
 * HTTP协议要求一问一答
 * 对此,这里的处理大致分为三步
 * 1:解析请求
 * 2:处理请求
 * 3:发送响应
 */
public class ClientHandler implements Runnable{
    private Socket socket;
    public ClientHandler(Socket socket){
        this.socket = socket;
    }

    public void run() {
        try {
            //1解析请求
            HttpServletRequest request = new HttpServletRequest(socket);
            //V7新增:在处理请求前先实例化响应对象
            HttpServletResponse response = new HttpServletResponse(socket);

            //2处理请求
            String path = request.getUri();
            System.out.println("抽象路径:"+path);
            File baseDir = new File(
                    ClientHandler.class.getClassLoader().getResource(".").toURI()
            );
            File staticDir = new File(baseDir,"static");
            File file = new File(staticDir,path);
            /*
                V7:将给浏览器发送的状态代码和对应的正文文件设置到响应对象中
                   这样以来,第三步发送时,就会按照这里设置的信息发送给浏览器了
             */
//            int statusCode;
//            String statusReason;
            if(file.isFile()){
//                statusCode=200;
//                statusReason="OK";
                //正确时不必设置状态代码和描述,响应对象内部默认就是200,OK
                //因为实际应用中绝大部分响应都是成功的,没必要每次都设置200,OK
                response.setContentFile(file);
            }else{
//                statusCode=404;
//                statusReason="NotFound";
                file = new File(staticDir,"404.html");
                response.setStatusCode(404);
                response.setStatusReason("NotFound");
                response.setContentFile(file);
            }

            //3发送响应
            /*
                V7:由于这里将发送响应的操作移动到了HttpServletResponse的response方法中了
                因此这里改为调用这个方法完成同等操作.
             */
            response.response();


        } catch (IOException | URISyntaxException e) {
            e.printStackTrace();
        } finally {
            //遵循HTTP协议要求,一问一答后与客户端断开连接
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }




}
